<template>
  <s-clean-layout title="礼簿列表" navbar="normal">  
    <view class="gift-book-container">
      <!-- 顶部标签页 -->
      <view class="tab-container">
        <view class="tab-item" :class="{ active: activeTab === 'receive' }" @tap="switchTab('receive')">
          收礼礼簿
          <view v-if="activeTab === 'receive'" class="tab-indicator"></view>
        </view>
        <view class="tab-item" :class="{ active: activeTab === 'send' }" @tap="switchTab('send')">
          送礼礼簿
          <view v-if="activeTab === 'send'" class="tab-indicator"></view>
        </view>
      </view>
      
      <!-- 功能按钮区域 -->
      <view class="function-area">
        <view class="function-buttons">
          <view class="delete-btn" v-if="selectedItems.length > 0" @tap="deleteSelected">
            <uni-icons type="trash" size="18" color="#666"></uni-icons>
          </view>
          <view class="sort-btn" @tap="toggleSortOptions">
            <uni-icons type="sort" size="18" color="#666"></uni-icons>
          </view>
          <view class="filter-btn" @tap="toggleFilterOptions">
            <uni-icons type="funnel" size="18" color="#666"></uni-icons>
          </view>
        </view>
      </view>
      
      <!-- 礼簿列表 - 改为卡片布局 -->
      <view class="gift-book-list">
        <view class="card-list">
          <view 
            class="card" 
            v-for="(item, index) in filteredGiftList" 
            :key="index"
            :class="{ 'inactive': item.amount === 0, 'selected': isItemSelected(item.id) }"
            @tap="viewGiftBookDetail(item.id)"
            :style="{'--card-color': item.coverColor || '#FF6B6B'}"
          >
            <view class="card-header">
              <view class="card-title">
                <text class="title">{{ item.bookName }}</text>
                <text class="count">共{{ item.count || 0 }}笔</text>
              </view>
              <view class="toggle" :class="{ 'inactive': item.amount === 0, 'selected': isItemSelected(item.id) }"></view>
            </view>
            <view class="card-info">
              <text class="amount" :class="{ 'inactive-amount': item.amount === 0 }">
                {{ item.transactionType === 'IN' ? '+' : '-' }}¥ {{ item.amount || 0 }}
              </text>
              <text class="date">{{ formatDate(item.eventDate) }}</text>
            </view>
          </view>
          
          <!-- 添加新礼簿 -->
          <view class="add-card" @tap="addNewGiftRecord">
            <uni-icons type="plusempty" size="32" color="#999" />
            <text>添加{{ activeTab === 'receive' ? '收' : '送' }}礼礼簿</text>
          </view>
        </view>
      </view>
    </view>
  </s-clean-layout>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { onShow} from '@dcloudio/uni-app';
import sheep from '@/sheep';
import GiftApi from '@/pages/money/api/gift';

// 当前激活的标签页
const activeTab = ref('receive');

// 礼簿数据
const giftBookList = ref([]);

// 已选中的项目
const selectedItems = ref([]);

// 排序和筛选选项
const sortOption = ref('date-desc'); // 默认按日期降序
const filterOption = ref('all'); // 默认显示全部

// 获取礼簿列表数据
const fetchGiftBookList = async () => {
  try {
    const transactionType = activeTab.value === 'receive' ? 'IN' : 'OUT';
    const response = await GiftApi.queryAccountBooks({
      transactionType: transactionType
    });
    
    if (response.code === 0 && response.data) {
      // 处理返回的数据，使用giftNum和giftAmount字段
      giftBookList.value = response.data.map(item => ({
        ...item,
        // 使用giftAmount替代amount
        amount: item.giftAmount || 0,
        // 使用giftNum替代count
        count: item.giftNum || 0,
        // 确保coverColor字段被保留
        coverColor: item.coverColor || (item.transactionType === 'IN' ? '#FF6B6B' : '#5a9cf8')
      }));
      
      console.log('礼簿列表数据:', giftBookList.value);
    } else {
      uni.showToast({
        title: response.msg || '获取礼簿列表失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取礼簿列表失败:', error);
    uni.showToast({
      title: '获取礼簿列表失败',
      icon: 'none'
    });
  }
};

// 切换标签页
const switchTab = (tab) => {
  activeTab.value = tab;
  selectedItems.value = []; // 切换标签页时清空选中项
  fetchGiftBookList(); // 重新获取数据
};

// 根据当前标签页和筛选条件获取列表数据
const filteredGiftList = computed(() => {
  let list = [...giftBookList.value];
  
  // 应用筛选
  if (filterOption.value !== 'all') {
    // 这里可以添加更多筛选逻辑
    const now = new Date();
    const currentYear = now.getFullYear();
    
    if (filterOption.value === 'this-year') {
      list = list.filter(item => {
        const itemDate = new Date(item.eventDate);
        return itemDate.getFullYear() === currentYear;
      });
    } else if (filterOption.value === 'last-year') {
      list = list.filter(item => {
        const itemDate = new Date(item.eventDate);
        return itemDate.getFullYear() === currentYear - 1;
      });
    }
  }
  
  // 应用排序
  list = [...list].sort((a, b) => {
    if (sortOption.value === 'date-desc') {
      return b.eventDate - a.eventDate;
    } else if (sortOption.value === 'date-asc') {
      return a.eventDate - b.eventDate;
    } else if (sortOption.value === 'amount-desc') {
      return b.amount - a.amount;
    } else if (sortOption.value === 'amount-asc') {
      return a.amount - b.amount;
    }
    return 0;
  });
  
  return list;
});

// 切换选中状态
const toggleSelectItem = (id) => {
  const index = selectedItems.value.indexOf(id);
  if (index === -1) {
    selectedItems.value.push(id);
  } else {
    selectedItems.value.splice(index, 1);
  }
};

// 检查项目是否被选中
const isItemSelected = (id) => {
  return selectedItems.value.includes(id);
};

// 删除选中项
const deleteSelected = async () => {
  try {
    // 这里应该调用删除API
    // 示例：
    // const response = await sheep.$api.app.gift.deleteAccountBooks({
    //   ids: selectedItems.value
    // });
    
    // 临时模拟删除成功
    giftBookList.value = giftBookList.value.filter(item => !selectedItems.value.includes(item.id));
    selectedItems.value = [];
    
    uni.showToast({
      title: '删除成功',
      icon: 'success'
    });
  } catch (error) {
    console.error('删除礼簿失败:', error);
    uni.showToast({
      title: '删除礼簿失败',
      icon: 'none'
    });
  }
};

// 切换排序选项
const toggleSortOptions = () => {
  uni.showActionSheet({
    itemList: ['按日期降序', '按日期升序', '按金额降序', '按金额升序'],
    success: function (res) {
      const options = ['date-desc', 'date-asc', 'amount-desc', 'amount-asc'];
      sortOption.value = options[res.tapIndex];
    }
  });
};

// 切换筛选选项
const toggleFilterOptions = () => {
  uni.showActionSheet({
    itemList: ['全部', '今年', '去年'],
    success: function (res) {
      const options = ['all', 'this-year', 'last-year'];
      filterOption.value = options[res.tapIndex];
    }
  });
};

// 添加新记录
const addNewGiftRecord = () => {
  // 修改：传递礼簿类型参数
  sheep.$router.go('/pages/money/gift-book-edit', {
    type: activeTab.value // 传递当前标签页类型：receive 或 send
  });
};

// 查看礼簿详情
const viewGiftBookDetail = (id) => {
  const item = filteredGiftList.value.find(item => item.id === id);
  if (item) {
    sheep.$router.go('/pages/money/gift-book-detail', {
      id: id,
      type: activeTab.value === 'receive' ? 'receive' : 'send',
      title: item.bookName,
      coverColor: item.coverColor // 传递封面颜色
    });
  }
};

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 页面加载时获取数据
onMounted(() => {
  // 获取页面参数，确定应该显示哪个标签页
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const params = currentPage.options || {};
  
  // 如果有type参数，则切换到对应的标签页
  if (params.type) {
    // 确保type参数值为receive或send
    if (params.type === 'receive' || params.type === 'send') {
      activeTab.value = params.type;
    }
  }
  
  // 不在onMounted中调用fetchGiftBookList，改为在onShow中统一处理
});

// 添加onShow生命周期钩子，每次页面显示时刷新数据
onShow(() => {
  console.log('礼簿列表页面显示，刷新数据');
  // 重新获取礼簿列表数据
  fetchGiftBookList();
});

// 移除goBack方法，因为使用s-clean-layout的返回功能
// const goBack = () => {
//   uni.navigateBack({
//     delta: 1
//   });
// };
</script>

<style lang="scss" scoped>
.gift-book-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;
}

/* 移除原有的header-container样式 */
/* .header-container {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 20rpx 0;
  border-bottom: 1px solid #eee;
} */

/* 移除原有的back-btn样式 */
/* .back-btn {
  padding: 20rpx;
  margin-right: 10rpx;
} */

.tab-container {
  display: flex;
  background-color: #fff;
  padding: 0;
  border-bottom: 1px solid #eee;
}

/* 其余样式保持不变 */
.tab-item {
  flex: 1;
  text-align: center;
  padding: 30rpx 0;
  font-size: 32rpx;
  position: relative;
  color: #666;
  
  &.active {
    color: #333;
    font-weight: bold;
  }
}

.tab-indicator {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 6rpx;
  background-color: #ff6000;
  border-radius: 3rpx;
}

.function-area {
  padding: 20rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.function-buttons {
  display: flex;
  justify-content: flex-end;
}

.delete-btn, .sort-btn, .filter-btn {
  margin-left: 30rpx;
  padding: 10rpx;
}

/* 礼簿列表样式 */
.gift-book-list {
  flex: 1;
  padding: 20rpx 30rpx;
}

.card-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}

.card, .add-card {
  width: 30%;
  margin-right: 5%;
  margin-bottom: 20rpx;
  padding: 20rpx 15rpx;
  background-color: #fff;
  border-radius: 12rpx 20rpx 20rpx 12rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  position: relative;
  transition: all 0.3s ease;
  overflow: hidden;
  box-sizing: border-box;
}

.card:nth-child(3n), .add-card:nth-child(3n) {
  margin-right: 0;
}

.card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 8rpx;
  height: 100%;
  background: var(--card-color, linear-gradient(to bottom, #FF6B6B, #FF8E53));
  border-radius: 4rpx 0 0 4rpx;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
  position: relative;
}

.card-title {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding-left: 10rpx;
}

.title {
  font-size: 28rpx;
  // font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 120rpx;
  color: #333;
}

.count {
  font-size: 22rpx;
  color: #999;
  margin-top: 6rpx;
}

.toggle {
  width: 30rpx;
  height: 16rpx;
  background: var(--card-color, linear-gradient(135deg, rgba(255, 107, 107, 0.8), rgba(255, 142, 83, 0.8)));
  border-radius: 8rpx;
  position: relative;
}

.toggle.inactive {
  background: #e8e8e8;
}

.toggle.selected {
  background: linear-gradient(135deg, rgba(76, 175, 80, 0.8), rgba(139, 195, 74, 0.8));
}

.card-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8rpx;
  padding-left: 10rpx;
}

.amount {
  font-size: 32rpx;
  // font-weight: bold;
  color: #FF6B6B;
}

.inactive-amount {
  color: #999;
}

.date {
  font-size: 20rpx;
  color: #999;
}

.add-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 15rpx;
  color: #999;
  font-size: 24rpx;
  border: 2rpx dashed #ddd;
  background-color: rgba(250, 250, 250, 0.8);
}

/* 卡片悬浮效果 */
.card:active {
  transform: translateY(-5rpx);
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.08);
}

.gift-book-row {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.gift-book-item {
  width: 30%;
  margin-bottom: 40rpx;
  box-sizing: border-box;
}

.book-cover {
  position: relative;
  height: 240rpx;
  perspective: 1000rpx;
  transform-style: preserve-3d;
  transition: all 0.3s ease;
  border-radius: 8rpx;
}

.book-spine {
  position: absolute;
  left: 0;
  top: 0;
  width: 16rpx;
  height: 100%;
  background-color: #ff6a6a;
  transform: rotateY(90deg) translateZ(-8rpx);
  transform-origin: left;
  border-radius: 2rpx 0 0 2rpx;
  transition: background-color 0.3s ease;
  box-shadow: inset -2rpx 0 4rpx rgba(0, 0, 0, 0.1);
}

.book-front {
  position: relative;
  height: 100%;
  background-color: #fff;
  border-radius: 0 8rpx 8rpx 0;
  box-shadow: 2rpx 4rpx 12rpx rgba(0, 0, 0, 0.1);
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border-left: 4rpx solid #ff6a6a;
  transform: translateZ(8rpx);
  overflow: hidden;
  transition: all 0.3s ease;
}

.book-status-bar {
  position: absolute;
  top: 0;
  right: 0;
  width: 6rpx;
  height: 100%;
  background-color: #ff6a6a;
}

.inactive-status {
  background-color: #cccccc;
}

.book-title {
  font-size: 28rpx;
  // font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.book-meta {
  font-size: 22rpx;
  color: #999;
}

.book-amount {
  font-size: 32rpx;
  // font-weight: bold;
  margin: 10rpx 0;
  
  &.amount-positive {
    color: #ff6a6a;
  }
  
  &.amount-negative {
    color: #5a9cf8;
  }
}

.book-date {
  font-size: 20rpx;
  color: #999;
}

.book-select-indicator {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  width: 36rpx;
  height: 36rpx;
  background-color: #ff6a6a;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2;
}

.active-book {
  transform: translateY(-5rpx);
  
  .book-front {
    border-color: #ff6a6a;
    box-shadow: 0 8rpx 20rpx rgba(255, 106, 106, 0.2);
  }
  
  .book-spine {
    background-color: #ff6a6a;
  }
}

.inactive-book {
  .book-front {
    border-color: #cccccc;
  }
  
  .book-spine {
    background-color: #cccccc;
  }
}

.inactive-front {
  border-color: #cccccc;
}

/* 添加新礼簿的样式 */
.add-book-cover {
  .book-spine {
    background-color: #e0e0e0;
  }
}

.add-book-front {
  border-color: #e0e0e0;
  justify-content: center;
  align-items: center;
  background-color: #f9f9f9;
  border-style: dashed;
  border-width: 2rpx;
}

.add-icon {
  font-size: 60rpx;
  color: #aaa;
  margin-bottom: 10rpx;
  line-height: 1;
}

.add-text {
  font-size: 24rpx;
  color: #aaa;
  text-align: center;
}

/* 悬浮效果 */
.gift-book-item:active .book-cover:not(.add-book-cover) {
  transform: translateY(-8rpx) rotateX(5deg);
  
  .book-front {
    box-shadow: 0 10rpx 25rpx rgba(0, 0, 0, 0.15);
  }
}
</style>